import * as constants from '@/config/constants';
import store from './store';
import {PEN_UP, RETURN_PEN_IMAGE} from '@/config/constants';
import { websiteConfig } from '@/config/website.config';
import { useCourse } from '@/store/modules/course';

export default class PenSocket extends WebSocket {
  public count = 0;
  public timer: any = null;
  public list: any[] = [];
  constructor(ws) {
    super(ws);
    super.onopen = (e) => this.sendReadyState();
    super.onmessage = (e) => this.handleMessage(JSON.parse(e.data));
    super.onerror = (e) => {
      this.sendReadyState();
      console.error('error', e);
    };
    super.onclose = (e) => {
      this.sendReadyState();
      console.error('close', e);
    };
  }
  handleMessage(data) {
    switch (data.msgId) {
      case constants.WEBSOCKET_CONNECT_SUCCESS:
        this.getBattery();
        this.getCodePointValue();
        this.getCodePointValue();
        this.getCodePointValue();
        break;
      case constants.PEN_OFFLINE_DATA_SIZE:
        store.worker.postMessage(constants.WORKER_GET_OFFLINE_SIZE_NUMBER, data);
        break;
      case constants.PEN_BATTERY:
        store.worker.postMessage(constants.WORKER_PEN_BATTERY, data);
        break;
      case constants.PEN_DATA:
        // console.log(data)
        store.worker.postMessage(constants.PEN_DATA, data);
        const point = data.data;
        // 落笔时，设置页面数据
        if (point.type === constants.PEN_DOWN) {
          store.pen.currentBookPageId = `${data.data.BookID}-${data.data.OwnerID}-${data.data.PageID}-${data.data.SectionID}`;
        }
        const tempX = point.x + point.fx / 100;
        const tempY = point.y + point.fy / 100;
        // 判断点是否在当前区域内
        // console.log(store.pen.getPageX(store.pen.currentRegion.left), tempX, store.pen.getPageX(store.pen.currentRegion.right))
        // console.log(store.pen.getPageY(store.pen.currentRegion.top), tempY, store.pen.getPageY(store.pen.currentRegion.bottom))
        const currentRegion = store.pen.currentRegion
        let currentRegionIndex = currentRegion.textBookId + '-' + currentRegion.regionId + '-' + currentRegion.index
        if (
          store.pen.getPageX(currentRegion.left) < tempX &&
          store.pen.getPageX(currentRegion.right) > tempX &&
          store.pen.getPageY(currentRegion.top) < tempY &&
          store.pen.getPageY(currentRegion.bottom) > tempY
        ) {
          // console.log('笔在旧的区域书写');
          // 如果格子书写完毕，不能写入新数据
          if (!store.tempPenData[currentRegionIndex].finished) {
            const nowDate = Date.now();
            // 如果新的笔迹距离上次超过3秒, 拒绝写入
            if (nowDate - store.tempPenData[currentRegionIndex].lastWriteTime < 3000) {
              store.tempPenData[currentRegionIndex].lastWriteTime = nowDate
              store.tempPenData[currentRegionIndex].data.push(point)

              store.lastPenData = store.tempPenData[currentRegionIndex]
              clearTimeout(this.timer)
              this.timer = setTimeout(() => {
                this.returnPenData(store.lastPenData)
                clearTimeout(this.timer)
              }, 3000)
            }

          };
        } else {
          // console.log('笔在新的区域书写');
          // console.log(store.tempPenData[currentRegionIndex])
          // 新区域书写时，将现有的笔迹数据传输给主线程，生成笔迹图片, 并且评分
          if (store.lastPenData?.data?.length > 0 && !store.lastPenData?.finished) {
            this.returnPenData(store.lastPenData)
          }
          const pageData = store.pen.bookMapData[store.pen.currentBookPageId];
          if (pageData && pageData.regionList) {
            for (let i = 0; i < pageData.regionList.length; i++) {
              const v = pageData.regionList[i];
              if (
                store.pen.getPageX(v.left) < tempX &&
                store.pen.getPageX(v.right) > tempX &&
                store.pen.getPageY(v.top) < tempY &&
                store.pen.getPageY(v.bottom) > tempY
              ) {
                store.pen.currentRegion = {
                  ...v,
                  width: v.right - v.left,
                  height: v.bottom - v.top,
                };
                currentRegionIndex = store.pen.currentRegion.textBookId + '-' + store.pen.currentRegion.regionId + '-' + store.pen.currentRegion.index
                if (!store.tempPenData[currentRegionIndex]) {
                  store.tempPenData[currentRegionIndex] = {
                    finished: false,
                    lastWriteTime: Date.now(),
                    data: [point]
                  }
                }

                break;
              }
            }
          }

        }

        if (!store.tempPenData[currentRegionIndex]?.finished) {
          store.pen.draw(point);
        }
        // this.count++;
        // if (this.count < 10) {
        //   this.list.push(point);
        // }
        // if (this.count === 10) {
        //   console.log(store.mac, this.list);
        // }

        break;
      case constants.AP_TEST:
        store.worker.postMessage(constants.AP_TEST, data);
        break;
      case constants.GET_PEN_AUTO_OFF:
        store.worker.postMessage(constants.GET_PEN_AUTO_OFF, data);
        break;
      case constants.SET_PEN_AUTO_OFF:
        store.worker.postMessage(constants.SET_PEN_AUTO_OFF, data);
        break;
      case constants.GET_CODE_POINT_VALUE:
        store.worker.postMessage(constants.GET_CODE_POINT_VALUE, data);
        console.log('更新码点信息', data.data)
        store.pen.codePoint = store.pen.getCodePoint(data.data);
        break;

      default:
        // console.log('default', data)
        break;
    }
  }
  returnPenData(obj){
    // 将笔记数据分组 落笔-移动-抬笔分为一组
    const groupPenData: any = [[]]
    let groupIndex = 0
    obj.data.forEach((item, i) => {
      if(i===0) {
        item.type = constants.PEN_DOWN
      }
      if(i===(obj.data.length - 1)) {
        item.type = constants.PEN_UP
      }
      if (item.type === constants.PEN_DOWN) {
        item.type = 0;
      } else if (item.type === constants.PEN_MOVE) {
        item.type = 1;
      } else {
        item.type = 2;
      }
      groupPenData[groupIndex].push(item)
      if (item.type === 2 && i < (obj.data.length - 1)) {
        groupIndex++;
        groupPenData[groupIndex] = []
      }
    })
    !obj.finished && store.worker.postMessage(constants.RETURN_PEN_IMAGE, {
      image: store.pen.getGridImage(),
      tempPenData: groupPenData,
      ...store.pen.currentRegion,
    });
    obj.finished = true;
    obj.data = [];
    store.pen.clearRegion();
  }
  // 发送WebSocket状态
  sendReadyState() {
    store.worker.postMessage(constants.WORKER_WEBSOCKET_READY_STATE, {
      readyState: super.readyState,
    });
  }
  // 获取离线数据量
  getOfflineDataNumber() {
    super.send(
      JSON.stringify({
        msgId: constants.PEN_OFFLINE_DATA_SIZE,
      })
    );
  }
  // 开始离线传输
  startOfflineTransfer() {
    super.send(
      JSON.stringify({
        msgId: constants.PEN_OFFLINE_START_STOP,
        status: constants.PEN_OFFLINE_START_STATUS,
      })
    );
  }
  // 暂停离线传输
  pauseOfflineTransfer() {
    super.send(
      JSON.stringify({
        msgId: constants.PEN_OFFLINE_PAUSE_CONTINUE,
        status: constants.PEN_OFFLINE_CONTINUE_STATUS,
      })
    );
  }
  // 继续离线传输
  continueOfflineTransfer() {
    super.send(
      JSON.stringify({
        msgId: constants.PEN_OFFLINE_PAUSE_CONTINUE,
        status: constants.PEN_OFFLINE_PAUSE_STATUS,
      })
    );
  }
  // 停止离线传输
  stopOfflineTransfer() {
    super.send(
      JSON.stringify({
        msgId: constants.PEN_OFFLINE_START_STOP,
        status: constants.PEN_OFFLINE_STOP_STATUS,
      })
    );
  }
  // 获取电池信息
  getBattery() {
    super.send(
      JSON.stringify({
        msgId: constants.PEN_BATTERY,
      })
    );
  }
  // 获取自动关机时间
  getAutoOffTime() {
    super.send(
      JSON.stringify({
        msgId: constants.GET_PEN_AUTO_OFF,
      })
    );
  }
  // 设置自动关机时间
  setAutoOffTime(data) {
    super.send(
      JSON.stringify({
        msgId: constants.SET_PEN_AUTO_OFF,
        data,
      })
    );
  }
  // 码点类型
  getCodePointValue() {
    super.send(
      JSON.stringify({
        msgId: constants.GET_CODE_POINT_VALUE,
      })
    );
  }
  // 测试命令
  test(data) {
    super.send(
      JSON.stringify({
        msgId: constants.AP_TEST,
        data,
      })
    );
  }
}
